package com.bee.auth.client.interceptor;

import com.alibaba.fastjson.JSON;
import com.bee.auth.client.AuthHolder;
import com.bee.auth.client.util.HttpSecurityUtil;
import com.bee.commons.enums.ErrCodeEnum;
import com.bee.commons.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author Damin.yang
 * @date 2019/08/17 16:46
 */
@RefreshScope
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final String SWAGGER = "swagger";

    @Value("${auth.jwt.signingKey}")
    private String secretKey;
    @Value("${auth.loginPage}")
    private String loginPage;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = HttpSecurityUtil.getToken(request);
        if (StringUtils.isBlank(token)) {
            token = HttpSecurityUtil.getClientToken(request);
            if (StringUtils.isBlank(token)) {
                tologin(request, response);
                return false;
            }
        }

        Map<String, Object> context = HttpSecurityUtil.parseJwtToken(token, secretKey);
        if (context == null) {
            tologin(request, response);
            return false;
        }

        context.put(AuthHolder.TOKEN, token);
        AuthHolder.set(context);

        return super.preHandle(request, response, handler);
    }

    private void tologin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String uri = request.getRequestURI();
        if (uri.contains(SWAGGER)) {
            response.sendRedirect(loginPage);
            return;
        }

        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(Result.fail(ErrCodeEnum.LOGOUT.getCode(), ErrCodeEnum.LOGOUT.getMsg())));
    }
}
